package com.ali.service.impl;

import com.ali.common.BeanCopyUtil;
import com.ali.common.Response;
import com.ali.dao.PayMapper;
import com.ali.dto.PayInfo;
import com.ali.entity.Pay;
import com.ali.service.PayService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Service
public class PayServiceImpl implements PayService {
    @Resource
    private PayMapper payMapper;

    @Override
    public Response<List<PayInfo>> query(Map<String, Object> param) {
        QueryWrapper<Pay> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("orderid", param.get("orderid"));
        List<Pay> pays = payMapper.selectList(queryWrapper);
        List<PayInfo> payInfos = BeanCopyUtil.copyListProperties(pays, PayInfo::new);
        return Response.success(payInfos);
    }

    @Override
    public Response<String> timeout() {
        log.info("开始时间：" + LocalDateTime.now());

        try {
            Thread.sleep(61000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        log.info("结束时间：" + LocalDateTime.now());

        return Response.success("hello");
    }

    @Override
    public Response<String> control(Map<String, Object> param) {
        log.info("control：" + param);
        log.info("开始时间：" + LocalDateTime.now());

        int num = 1;

        Object numObject = param.get("num");
        if (numObject != null) {
            num = Integer.parseInt((String) numObject);
        }

        if (num == -1) {
            log.info("手动抛出异常");
            throw new RuntimeException("手动抛出异常");
        } else if (num == 0) {
            log.info("休眠5秒钟");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

        log.info("结束时间：" + LocalDateTime.now());

        return Response.success("hello");
    }

    @Override
    public Response<String> print(Map<String, Object> param, Map<String, Object> header) {
        log.info("param：" + param);
        log.info("header：" + header);
        return Response.success("hello");
    }

    @Override
    public Response<String> add(Map<String, Object> param) {
        String payno = (String) param.get("payno");
        if (Objects.equals("test", payno)) {
            throw new RuntimeException("测试事务，手动抛出异常");
        }

        Pay pay = new Pay();
        pay.setOrderId(Long.parseLong(String.valueOf(param.get("orderid"))));
        pay.setPayNo(payno);
        pay.setPayMoney(Integer.parseInt((String) param.get("paymoney")));

        payMapper.insert(pay);
        return Response.success("增加成功");
    }
}